package com.tuanzi.loan.business.repository.statistics.impl;

import static com.tuanzi.loan.generated.jooq.stat.tables.NginxUrlUvStat.NGINX_URL_UV_STAT;
import static com.tuanzi.loan.generated.jooq.stat.tables.StatActivityJoin.STAT_ACTIVITY_JOIN;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import org.apache.commons.lang3.StringUtils;
import org.jooq.Condition;
import org.jooq.GroupField;
import org.jooq.SelectField;
import org.jooq.SelectQuery;
import org.jooq.impl.DSL;
import org.jooq.impl.TableImpl;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;

import com.tuanzi.loan.business.repository.statistics.NginxLinkStatRepository;
import com.tuanzi.loan.core.repository.JOOQBaseRepositoryPlus;
import com.tuanzi.loan.vo.request.statistics.NginxLinkStatRequest;
import com.tuanzi.loan.vo.response.statistics.NginxLinkStatResponse;


/**
 * nginx链接统计
 * @author JinRuiyang 2018/02/02
 */
@Repository
public class NginxLinkStatRepositoryImpl extends JOOQBaseRepositoryPlus implements NginxLinkStatRepository {
	
	private static final String ALL_FIELD_ID = "'-1000'";
	
	public NginxLinkStatResponse getAllListDataSum(NginxLinkStatRequest searchRequest) {
		Condition condition = DSL.trueCondition();
        List<SelectField<?>> selectFields = new ArrayList<>();
        
        if (Objects.nonNull(searchRequest.getStartDate())) {
            condition = condition.and(NGINX_URL_UV_STAT.CDATE.ge(new java.sql.Date(searchRequest.getStartDate().getTime())));
        }
        if (Objects.nonNull(searchRequest.getEndDate())) {
        	condition = condition.and(NGINX_URL_UV_STAT.CDATE.le(new java.sql.Date(searchRequest.getEndDate().getTime())));
        }
        
        if(!(Objects.isNull(searchRequest.getPlatform()) || searchRequest.getPlatform().isEmpty()) 
        		&& !"-1000".equals(searchRequest.getPlatform())) {
        	condition = condition.and(NGINX_URL_UV_STAT.PLATFORM.in(searchRequest.getPlatform()));
        } 
        
        if(!(Objects.isNull(searchRequest.getRequestMethod()) || searchRequest.getRequestMethod().isEmpty())
        		&& !"-1000".equals(searchRequest.getRequestMethod())) {
        	condition = condition.and(NGINX_URL_UV_STAT.REQUEST_METHOD.in(searchRequest.getRequestMethod()));
        } 
        
        if (StringUtils.isNotEmpty(searchRequest.getUrl())){
            condition = condition.and(NGINX_URL_UV_STAT.URL.contains(searchRequest.getUrl()));
        } 
		
        SelectQuery selectQuery = dslContext.select(DSL.sum(NGINX_URL_UV_STAT.UV).as("uvSum"))
                .select(DSL.sum(NGINX_URL_UV_STAT.PV).as("pvSum"))
                .from(NGINX_URL_UV_STAT)
                .where(condition)
                .getQuery();
        
        List<NginxLinkStatResponse> sumList = selectQuery.fetch(record -> {
    		NginxLinkStatResponse response = new NginxLinkStatResponse();
    		if(!record.toString().contains("null")) {
    			response.setUvSum(record.get(0,Long.class));
    			response.setPvSum(record.get(1,Long.class));
    		}
            return response;
        });
        
        NginxLinkStatResponse sumResult = new NginxLinkStatResponse();
        if(sumList !=null && sumList.size() == 1) {
        	sumResult.setUvSum(sumList.get(0).getUvSum());
        	sumResult.setPvSum(sumList.get(0).getPvSum());
        }
        
		return sumResult;
	}

    public List<NginxLinkStatResponse> getAllList(NginxLinkStatRequest searchRequest) {
    	SelectQuery selectQuery = getSelectQueryByActivityJoin(searchRequest);
    	List<NginxLinkStatResponse> resultList = selectQuery.fetch(record -> {
    		NginxLinkStatResponse response = new NginxLinkStatResponse();
			response.setCdate(record.get(0,Date.class));
			
			String platform = record.get(1,String.class);
			if("-1000".equals(platform)) {
				response.setPlatform("全部");
			} else {
				response.setPlatform(platform);
			}
			
			String requestMethod = record.get(2,String.class);
			if("-1000".equals(requestMethod)) {
				response.setRequestMethod("全部");
			} else {
				response.setRequestMethod(requestMethod);
			}
			
			response.setUrl(record.get(3,String.class));
			response.setUv(record.get(4,Integer.class));
			response.setPv(record.get(5,Integer.class));
            return response;
        });
    	return resultList;
    }
    
    public Page<NginxLinkStatResponse> getlistPageByActivityJoin(NginxLinkStatRequest searchRequest,
			Pageable pageable) {
    	SelectQuery selectQuery = getSelectQueryByActivityJoin(searchRequest);
		return search(selectQuery, pageable, record ->{
			NginxLinkStatResponse response = new NginxLinkStatResponse();
			response.setCdate(record.get(0,Date.class));
			
			String platform = record.get(1,String.class);
			if("-1000".equals(platform)) {
				response.setPlatform("全部");
			} else {
				response.setPlatform(platform);
			}
			
			String requestMethod = record.get(2,String.class);
			if("-1000".equals(requestMethod)) {
				response.setRequestMethod("全部");
			} else {
				response.setRequestMethod(requestMethod);
			}
			
			response.setUrl(record.get(3,String.class));
			response.setUv(record.get(4,Integer.class));
			response.setPv(record.get(5,Integer.class));
			return response;
		});
	}
	
	public SelectQuery getSelectQueryByActivityJoin(NginxLinkStatRequest searchRequest) {
		Condition condition = DSL.trueCondition();
        List<SelectField<?>> selectFields = new ArrayList<>();
        List<GroupField> groupFields = new ArrayList<>();
        
        selectFields.add(NGINX_URL_UV_STAT.CDATE);
        groupFields.add(NGINX_URL_UV_STAT.CDATE);
        groupFields.add(NGINX_URL_UV_STAT.URL);
        if (Objects.nonNull(searchRequest.getStartDate())) {
            condition = condition.and(NGINX_URL_UV_STAT.CDATE.ge(new java.sql.Date(searchRequest.getStartDate().getTime())));
        }
        if (Objects.nonNull(searchRequest.getEndDate())) {
        	condition = condition.and(NGINX_URL_UV_STAT.CDATE.le(new java.sql.Date(searchRequest.getEndDate().getTime())));
        }
        
        if(Objects.isNull(searchRequest.getPlatform()) || searchRequest.getPlatform().isEmpty()) {
        	selectFields.add(NGINX_URL_UV_STAT.PLATFORM);
        	groupFields.add(NGINX_URL_UV_STAT.PLATFORM);
        } else if(isSelectQueryAll(searchRequest.getPlatform())) {
        	selectFields.add(DSL.field(ALL_FIELD_ID).as("platform"));
        } else {
        	selectFields.add(NGINX_URL_UV_STAT.PLATFORM);
            condition = condition.and(NGINX_URL_UV_STAT.PLATFORM.in(searchRequest.getPlatform()));
            groupFields.add(NGINX_URL_UV_STAT.PLATFORM);
        }
        
        if(Objects.isNull(searchRequest.getRequestMethod()) || searchRequest.getRequestMethod().isEmpty()) {
        	selectFields.add(NGINX_URL_UV_STAT.REQUEST_METHOD);
        	groupFields.add(NGINX_URL_UV_STAT.REQUEST_METHOD);
        } else if(isSelectQueryAll(searchRequest.getRequestMethod())) {
        	selectFields.add(DSL.field(ALL_FIELD_ID).as("request_method"));
        } else {
        	selectFields.add(NGINX_URL_UV_STAT.REQUEST_METHOD);
            condition = condition.and(NGINX_URL_UV_STAT.REQUEST_METHOD.in(searchRequest.getRequestMethod()));
            groupFields.add(NGINX_URL_UV_STAT.REQUEST_METHOD);
        }
        
        if (StringUtils.isNotEmpty(searchRequest.getUrl())){
        	selectFields.add(NGINX_URL_UV_STAT.URL);
            condition = condition.and(NGINX_URL_UV_STAT.URL.contains(searchRequest.getUrl()));
        } else {
        	selectFields.add(NGINX_URL_UV_STAT.URL);
        }
		
		return dslContext.select(selectFields)
        		.select(DSL.sum(NGINX_URL_UV_STAT.UV).as("uv"))
                .select(DSL.sum(NGINX_URL_UV_STAT.PV).as("pv"))
                .from(NGINX_URL_UV_STAT)
                .where(condition)
                .groupBy(groupFields)
                .orderBy(NGINX_URL_UV_STAT.CDATE.desc())
                .getQuery();
	} 
	
	/******检查是否查询全部*********/
    public boolean isSelectQueryAll(String select) {
    	if(StringUtils.isEmpty(select)) {
    		return false;
    	}
    	if("-1000".equals(select)) {
			return true;
		}
    	return false;
    }

    @Override
    protected TableImpl getTable() {
        return NGINX_URL_UV_STAT;
    }
}
